#!/bin/bash

# 此脚本需要在数据库节点执行，包括检测mysql进程状态、端口状态、数据库连接数

# 系统ID
system_id=$(cat config.cnf | grep SystemId | awk -F "=" '{print $2}')
# 告警存放文件夹
alert_dir=$(cat config.cnf | grep AlertDir | awk -F "=" '{print $2}')
# 执行周期
execute_cycle=$(cat config.cnf | grep ExecuteCycle | awk -F "=" '{print $2}')
# 告警缓存文件
alarm_file_tmp="mariadb_check_alarm.txt"
echo -n "" >${alarm_file_tmp}
# 本机ip
local_ip=$(ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:")
# MariaDB端口
mariadb_port=$(cat config.cnf | grep MariaDBPort | awk -F "=" '{print $2}')
mariadb_conn_num=$(cat config.cnf | grep MariaDBConnNum | awk -F "=" '{print $2}')

# mariadb运行状态监控
mariadb_status_check() {
    systemctl status mariadb | grep -o running >> /dev/null 
    # 检查状态是否为 active
    if [[ $? -ne 0 ]]; then
        # 非active状态进行告警
       ./gen_alarm.sh -g "应用进程监控" "MariaDB服务运行状态异常,MariaDB进程不存在,IP:$(hostname -I)" 3 "MariaDB进程" "mariadb_pro" ${alarm_file_tmp}
    else
        # 状态正常且存在状态告警，则需要恢复告警
        ./gen_alarm.sh -r "应用进程监控" "MariaDB进程恢复正常,IP:$(hostname -I)" "MariaDB进程" "mariadb_pro" ${alarm_file_tmp}

        # 端口检查
        mariadb_port_check
		# 数据库连接数
		mariadb_conn_num_check
    fi
}

# mariadb运行端口监控
mariadb_port_check() {
    port=$(netstat -nplt | grep ":${mariadb_port} ")
    if [[ ${port} == '' ]]; then
        # 端口未监听，告警
        ./gen_alarm.sh -g "端口状态" "MariaDB服务端口[${mariadb_port}]未监听,IP:$(hostname -I)" 3 "MariaDB端口状态" "mariadb_port" ${alarm_file_tmp}
    else
        # 端口正常且存在告警，需要恢复告警
        ./gen_alarm.sh -r "端口状态" "MariaDB服务端口[${mariadb_port}]恢复正常,IP:$(hostname -I)" "MariaDB端口状态" "mariadb_port" ${alarm_file_tmp}
    fi
}

# 数据库连接数
mariadb_conn_num_check() {
    conn_num=$(mysqladmin -u root -paq1SW2dxyg status | awk '{print $4}')
    if [[ ${conn_num} -gt ${mariadb_conn_num} ]]; then
        # 连接数超出阈值
        ./gen_alarm.sh -g "服务数监控" "MariaDB连接数超出阈值${mariadb_conn_num},当前连接数${conn_num},IP:$(hostname -I)" 2 "MariaDB连接数" "mariadb_conn_num" ${alarm_file_tmp}
    else
        # 恢复告警
        ./gen_alarm.sh -r "服务数监控" "MariaDB连接数恢复正常,阈值${mariadb_conn_num},当前连接数${conn_num},IP:$(hostname -I)" "MariaDB端口状态" "mariadb_conn_num" ${alarm_file_tmp}
    fi
}

while true; do
    holidays_date=$(cat config.cnf | grep Holidays | awk -F "=" '{print $2}' | sed "s/,/ /g")
	current_date=$(date +'%Y-%m-%d')
	echo $holidays_date | grep -o $current_date >> /dev/null
	if [[ $? -eq 0 ]]; then
		exit 0
	else
		echo -n "" >${alarm_file_tmp}
		mariadb_status_check
		
		# 将缓存告警放入告警文件夹
		./gen_alarm.sh -s ${alarm_file_tmp}
		sleep ${execute_cycle}
	fi
done

